package com.h4313.ghome.ui.fragments;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.h4313.ghome.GHomeApplication;
import com.h4313.ghome.R;
import com.h4313.ghome.io.AvailableSourcesTask;
import com.h4313.ghome.io.AvailableSourcesTask.AvailableSourcesCallback;
import com.h4313.ghome.model.Capteur;
import com.h4313.ghome.ui.NewModuleCreation;
import com.h4313.ghome.ui.adapters.CapteursAdapter;

public class CreateTemperatureFragment extends Fragment implements TextWatcher,
		AvailableSourcesCallback {

	protected EditText mEditTempSeuil;
	protected TextView mTvWarningTempSeuil;
	protected MenuItem mBtnTempSeuil;
	protected boolean warning;
	private NewModuleCreation mCreation;
	private View mWait;

	private Spinner mSpinner;

	final static Integer TEMP_SEUIL_MAX = 50;
	final static Integer TEMP_SEUIL_MIN = 5;

	private final static String MODULE_NAME = "name";

	public static CreateTemperatureFragment newInstance(String name) {
		CreateTemperatureFragment frag = new CreateTemperatureFragment();
		Bundle bundle = new Bundle();
		bundle.putString(MODULE_NAME, name);
		frag.setArguments(bundle);
		return frag;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_create_temperature,
				container, false);
		
		mSpinner = (Spinner) view.findViewById(R.id.sp_capt_temp);
		mSpinner.setEnabled(false);

		mEditTempSeuil = (EditText) view.findViewById(R.id.ed_temp_seuil);
		mEditTempSeuil.addTextChangedListener(this);
		mTvWarningTempSeuil = (TextView) view
				.findViewById(R.id.tv_warning_temp_seuil);
		mTvWarningTempSeuil.setVisibility(View.INVISIBLE);
		
		mWait = view.findViewById(R.id.sp_wait);
		warning = false;

		return view;
	}

	@Override
	public void onAvailableSourcesFound(HashMap<String, List<Capteur>> capteurs) {
		
		if (getActivity() == null || isDetached()) {
			return;
		}
		
		// remove the progressBar for data has been retrieved...
			mWait.setVisibility(View.GONE);
			// ...and then process the data

			ArrayList<Capteur> items = new ArrayList<Capteur>();

			for (String type : capteurs.keySet()) {
				if ("temperature".equals(type)) {
					if (capteurs.get(type).isEmpty()) {
						// no capteur is available for the specified
						// type. A pop-up is shown, advising the
						// user
						AlertDialog.Builder builder = new AlertDialog.Builder(
								getActivity());
						builder.setPositiveButton("OK", new OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// nothing to do. User
								// clicked "OK", OK ?
							}
						});
						builder.setMessage(String
								.format(getResources().getString(
										R.string.no_capteur_available), type));
						builder.setTitle(R.string.no_capteur_available_title);
						builder.create().show();
					} else {
						mSpinner.setEnabled(true);
						for (Capteur c : capteurs.get(type)) {
							// format capteurs informations to suit the
							// spinner
							items.add(c);
						}
						CapteursAdapter adapter = new CapteursAdapter(
							getActivity(), items);
						mSpinner.setAdapter(adapter);
					}
				}
		}
	}

	@Override
	public void onStart() {
		super.onStart();

		AvailableSourcesTask task = new AvailableSourcesTask(this,
				getActivity());

		String moduleName = getArguments().getString(MODULE_NAME);
		task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, GHomeApplication.SERVER_URL + "/modules/" + moduleName
				+ "/sources");
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		super.onCreateOptionsMenu(menu, inflater);
		inflater.inflate(R.menu.fragment_create_morning_conf, menu);

		mBtnTempSeuil = menu.findItem(R.id.menu_create_morning_conf);
		mBtnTempSeuil.setEnabled(false);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.menu_create_morning_conf) {
			createModule();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		if (!(activity instanceof NewModuleCreation)) {
			throw new RuntimeException(
					"activity must implement NewModuleCreation");
		} else {
			mCreation = (NewModuleCreation) activity;
		}
	}

	@Override
	public void afterTextChanged(Editable arg0) {
	}

	@Override
	public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
			int arg3) {
	}

	@Override
	public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

		try {
			Integer tempSeuil = Integer.parseInt(mEditTempSeuil.getText()
					.toString());
			// Integer tempSeuil = mEditTempSeuil.get
			if (tempSeuil < TEMP_SEUIL_MAX && tempSeuil > TEMP_SEUIL_MIN
					&& warning == true) {
				warning = false;
				mTvWarningTempSeuil.setVisibility(View.INVISIBLE);
			} else {

				if (tempSeuil < TEMP_SEUIL_MIN) {
					mTvWarningTempSeuil.setVisibility(View.VISIBLE);
					mTvWarningTempSeuil
							.setText("Votre température seuil semble trop basse");
					warning = true;
				} else if (tempSeuil > TEMP_SEUIL_MAX) {
					mTvWarningTempSeuil.setVisibility(View.VISIBLE);
					mTvWarningTempSeuil
							.setText("Votre température seuil semble trop élevée");
					warning = true;
				}

			}

			if (mBtnTempSeuil != null) {
				mBtnTempSeuil.setEnabled((!warning && mSpinner.isEnabled()));
			}
		} catch (NumberFormatException nfe) {

			mTvWarningTempSeuil.setVisibility(View.INVISIBLE);

			if (mBtnTempSeuil != null) {
				mBtnTempSeuil.setEnabled(false);
			}
		}
	}

	private void createModule() {
		Map<String, String> params = new HashMap<String, String>();
		// TODO
		params.put("temperature", String.valueOf(((Capteur) mSpinner
				.getSelectedItem()).getIdCapteur()));
		String temperature = mEditTempSeuil.getText().toString();

		params.put("threshold", temperature);
		mCreation.createModule("monitoring_temperature", params);
	}
}
